import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/http_server/user_follower.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/viewmode/mine_user_info_viewmodel.dart';
import 'package:loxen/mode/mine/user_follower_list.dart';

class FollowerWidget extends StatelessWidget {

  const FollowerWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<_FollowerViewModel>(create: (context) {
      String userId = Provider.of<MineUserInfoViewModel>(context, listen: false)
          .user
          .id
          .toString();
      return _FollowerViewModel(userId);
    }, builder: (context, _) {
      BaseState state = context
          .select<_FollowerViewModel, BaseState>((value) => value.mState);
      List<Widget> listW = [];
      listW.add(Padding(
        padding: EdgeInsets.only(left: 36.w, top: 39.h),
        child: Text(
          '关注的人',
          style: TextStyle(
            fontSize: 32.sp,
            color: Theme.of(context).textTheme.bodyText2.color,
            fontWeight: FontWeight.bold,
          ),
        ),
      ));
      if (state == BaseState.LOADING) {
        listW.add(Container(
          height: 470.h,
          child: Center(
            child: Container(
              width: 50.w,
              height: 50.w,
              child: CircularProgressIndicator(),
            ),
          ),
        ));
      }
      if (state == BaseState.EMPTY) {
        listW.add(Container(
          padding: EdgeInsets.only(top: 40.h),
          height: 470.h,
          child: Center(
            child: Column(
              children: <Widget>[
                Image.asset(
                  "images/empty.png",
                  width: 257.w,
                  height: 240.h,
                ),
                Text(
                  "没有关注的人",
                  style: TextStyle(
                    fontSize: 24.sp,
                    color: Color(0X9982868E),
                  ),
                )
              ],
            ),
          ),
        ));
      }
      if (state == BaseState.FAIL) {
        listW.add(Container(
          padding: EdgeInsets.only(top: 40.h),
          height: 470.h,
          child: Center(
            child: Column(
              children: <Widget>[
                Image.asset(
                  "images/fail.png",
                  width: 257.w,
                  height: 240.h,
                ),
                Text(
                  "网络异常",
                  style: new TextStyle(
                    fontSize: 24.sp,
                    color: Color(0X9982868E),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 10.h),
                  child: SizedBox(
                    width: 260.w,
                    height: 92.h,
                    child: new OutlineButton(
                      color: Colors.white,
                      textColor: Color(0XFF0CABCB),
                      child: new Text('点我'),
                      onPressed: () {
                        context.read<_FollowerViewModel>().loadData();
                      },
                      borderSide: BorderSide(
                          color: Colors.blue,
                          width: 1.w,
                          style: BorderStyle.solid),
                    ),
                  ),
                )
              ],
            ),
          ),
        ));
      }
      if (state == BaseState.CONTENT) {
        return Builder(builder: (context) {
          List<Widget> listW = [];
          listW.add(Padding(
            padding: EdgeInsets.only(left: 36.w, top: 39.h),
            child: Text(
              '关注的人',
              style: TextStyle(
                fontSize: 32.sp,
                color: Theme.of(context).textTheme.bodyText2.color,
                fontWeight: FontWeight.bold,
              ),
            ),
          ));
          var data = context
              .select<_FollowerViewModel, List<Follower>>((value) => value.data)
              .map((item) {
            return Column(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.fromLTRB(42.w, 40.h, 80.w, 40.h),
                  child: Row(
                    children: <Widget>[
                      GestureDetector(
                        onTap: () {
                          Navigator.of(context).pushNamed(Routes.mine_user_info,
                              arguments: item.user.userId.toString());
                        },
                        child: CircleAvatar(
                          radius: 60.w,
                          backgroundImage: NetworkImage(item.user.portrait),
                        ),
                      ),
                      Expanded(
                        child: Padding(
                          padding: EdgeInsets.only(left: 26.w),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              Text(
                                item.user.nickname,
                                style: TextStyle(
                                    fontSize: 32.sp,
                                    color: Theme.of(context)
                                        .textTheme
                                        .bodyText2
                                        .color,
                                    fontWeight: FontWeight.bold),
                              ),
                              Padding(
                                padding: EdgeInsets.only(top: 10.h),
                                child: Text(
                                  item.user.desc != null &&
                                          item.user.desc.trim() != ''
                                      ? item.user.desc
                                      : '这个人很懒什么都没有留下',
                                  style: TextStyle(
                                    fontSize: 22.sp,
                                    color: Color(0xFF999999),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                      Container(
                        width: 150.w,
                        height: 50.h,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(5.w)),
                          border: Border.all(
                            color: Color(0xFF82868E),
                            width: 1.w,
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Image.asset(
                              item.mutual_following == 0
                                  ? 'images/mine_follow.png'
                                  : 'images/mine_follow_2.png',
                              width: 30.w,
                              height: 24.h,
                            ),
                            Text(item.mutual_following == 0 ? '已关注' : '相互关注',
                                style: TextStyle(
                                    color: Color(0xFF82868E),
                                    fontWeight: FontWeight.w500,
                                    fontSize: 12,
                                    height: 1))
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(left: 36.w, right: 36.w),
                  color: Color(0xFFEBECF1),
                  width: double.infinity,
                  height: 0.5,
                )
              ],
            );
          }).toList();
          listW.addAll(data);
          if (Provider.of<_FollowerViewModel>(context, listen: false)
              .isNext()) {
            listW.add(loadButton(() {
              Provider.of<_FollowerViewModel>(context, listen: false).next();
            }));
          }
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: listW,
          );
        });
      }

      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: listW,
      );
    });
  }

  Widget loadButton(Function() onClick) {
    ValueNotifier<bool> _click = ValueNotifier(false);
    return ValueListenableProvider.value(
        value: _click,
        child: GestureDetector(
          onTap: () {
            if (!_click.value) {
              onClick.call();
              _click.value = true;
            }
          },
          child: Container(
            width: double.infinity,
            height: 120.h,
            child: Center(
              child: Builder(
                builder: (BuildContext context) {
                  bool click = context.watch<bool>();
                  return click
                      ? Container(
                          width: 50.w,
                          height: 50.w,
                          child: CircularProgressIndicator(),
                        )
                      : Text(
                          '更多关注',
                          style: TextStyle(
                              fontSize: 24.sp,
                              color: Color(
                                0xFF999999,
                              )),
                        );
                },
              ),
            ),
          ),
        ));
  }
}

class _FollowerViewModel extends BaseViewModel with UserFollowerMixin {
  final String userId;

  int pageSize = 3;
  int page = 1;
  List<Follower> data;
  FollowerList followerList;

  _FollowerViewModel(this.userId) {
    loadData();
  }

  void unFollowerSB(Follower follower, {Function(String error) onError}) {
    unFollowerUser(follower.user.userId.toString()).listen((event) {
      if (event == 200) {
        follower.mutual_following = 0;
        notifyListeners();
      } else {
        if (onError != null) onError.call("取消关注失败");
      }
    }, onError: (error, stack) {
      if (onError != null) onError.call("网络异常");
      print(error);
      print(stack);
    });
  }

  void followerSB(Follower follower, {Function(String error) onError}) {
    followerUser(follower.user.userId.toString()).listen((event) {
      if (event == 201) {
        follower.mutual_following = 1;
        notifyListeners();
      } else {
        if (onError != null) onError.call("关注失败");
      }
    }, onError: (error, stack) {
      if (onError != null) onError.call("网络异常");
      print(error);
      print(stack);
    });
  }

  void next() {
    if (isNext()) {
      page += 1;
      userFollowerList(
              userId: userId,
              page: page.toString(),
              pageSize: pageSize.toString())
          .listen((event) {
        if (event != null) {
          followerList = event;
          data = data.take(data.length).toList();
          data.addAll(event.results);
          notifyListeners();
        }
      }, onError: (error, stack) {
        print(error);
        print(stack);
      });
    }
  }

  bool isNext() {
    return followerList != null && followerList.next.trim() != '';
  }

  void loadData() {
    userFollowerList(userId: userId, pageSize: pageSize.toString())
        .doOnListen(() {
      mState = BaseState.LOADING;
      notifyListeners();
    }).listen((event) {
      if (event != null && event.results != null && event.results.length > 0) {
        followerList = event;
        data = event.results;
        mState = BaseState.CONTENT;
      } else {
        mState = BaseState.EMPTY;
      }
    }, onError: (error, stack) {
      mState = BaseState.FAIL;
      print(error);
      print(stack);
    }, onDone: () => notifyListeners());
  }
}
